package com.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.ali")
    public DataSource aliDB() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.local")
    public DataSource localDB() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }

    @Bean
    @Primary
    @DependsOn(value = {"aliDB", "localDB"})
    public DataSource getDB() {
        DataSourceRouting routing = new DataSourceRouting();
        Map<Object, Object> dbMap = new HashMap<>();
        dbMap.put("aliDB", aliDB());
        dbMap.put("localDB", localDB());
        routing.setTargetDataSources(dbMap);
        routing.setDefaultTargetDataSource(localDB());
        return routing;
    }

}
